package com.ct.controller.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.ct.controller.upload.contants.AliyunOssConstans;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {

	@Override
	public String upload(MultipartFile file, String fileHost, String oldName) {

		if (file == null) {
			return "上传的文件不允许为空!";
		}

		if (file.getSize() > 4 * 1024 * 1024) {
			return "文件上传的大小不能超过3M";
		}

		//获取阿里云存储相关常量
		String endPoint = AliyunOssConstans.endPoint;
		String accessKeyId = AliyunOssConstans.accessKeyId;
		String accessKeySecret = AliyunOssConstans.accessKeySecret;
		String bucketName = AliyunOssConstans.bucketName;
		String uploadUrl = null;

		try {
			//判断oss实例是否存在：如果不存在则创建，如果存在则获取
			OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
			if (!ossClient.doesBucketExist(bucketName)) {
				//创建bucket
				ossClient.createBucket(bucketName);
				//设置oss实例的访问权限：公共读
				ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
			}

			//获取上传文件流
			InputStream inputStream = file.getInputStream();
			//构建日期路径：avatar/2020/02/26/文件名
			String filePath = new DateTime().toString("yyyy/MM/dd");
			//文件名：uuid.扩展名
			String newName = "";
			if (StringUtils.isEmpty(oldName)) {
				String original = file.getOriginalFilename();
				String fileName = UUID.randomUUID().toString();
				String fileType = original.substring(original.lastIndexOf("."));
				newName = fileName + fileType;
			} else {
				newName = oldName;
			}
			String fileUrl = fileHost + "/" + filePath + "/" + newName;
			//文件上传至阿里云
			ossClient.putObject(bucketName, fileUrl, inputStream);
			// 关闭OSSClient。
			ossClient.shutdown();
			//获取url地址，注意https
			uploadUrl = "https://" + bucketName + "." + endPoint + "/" + fileUrl;
		} catch (IOException io) {
			throw new RuntimeException("OSS文件上传失败");
		}
		return uploadUrl;
	}

}